import json
from django_redis import get_redis_connection
from django.http import JsonResponse
from meiduo_mall.utils.cookiesecret import CookieSecret
def merge_cart_cookie_to_redis(request,response):
    """登录后合并购物车数据
    :param request: 本次请求对象，获取cookie中的数据
    :param response: 本次响应对象，清除cookie中的数据
    :return: response"""

    # dict ={
    #     16 :{
    #         'count': 2,
    #         'selected': True
    #     }
    # }
    # cookie_str = CookieSecret.dumps(cart_dict)
    user = request.user
    cookie_str = request.COOKIES.get('carts')
    if not cookie_str:
        return JsonResponse({
            'code': 400,
            'errmsg': '数据有误'
        })
    redis_conn = get_redis_connection('carts')
    cookie_dict = CookieSecret.loads(cookie_str)
    print(cookie_dict)
    for sku_id in cookie_dict:
        if cookie_dict.get(sku_id).get('selected'):
            redis_conn.sadd('selected_%s'%user.id,sku_id)
        redis_conn.hset('carts_%s' % user.id,sku_id,cookie_dict.get(sku_id).get('count'))
    response.delete_cookie('carts')
